﻿using System;
using System.Collections.Generic;
using NHibernate;
using SimpleScrum.Core.Entities;
using SimpleScrum.Helpers;
using SimpleScrum.Utils;

namespace SimpleScrum.Areas.Scrum.Models
{
    public class SprintModel
    {
        private ISession _session;

        public IList<Sprint> GetSprints(Guid projectId)
        {
            IList<Sprint> sprints;
            using (_session = NHibernateHelper.GetSession())
            {
                //NHibernate query 
                IQuery query =
                    _session.CreateQuery("from Sprint where ProjectId='" + projectId + "';");
                sprints = query.List<Sprint>();
            }
            return sprints;
        }

        public Sprint GetSprintById(Guid id)
        {
            var sprint = new Sprint();
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    sprint = _session.Get<Sprint>(id);
                    tran.Commit();
                }
            }
            return sprint;
        }

        public bool NewSprint(Sprint sprint)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    //sprint.ProjectId = CurrentProject;
                    _session.Save(sprint);
                    tran.Commit();
                }
            }
            return true;
        }

        public void UpdateSprint(Sprint sprint)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    //sprint.ProjectId = CurrentProject;
                    _session.Update(sprint);
                    tran.Commit();
                }
            }
        }

        public void DeleteSprint(Sprint sprint)
        {
            using (_session = NHibernateHelper.GetSession())
            {
                using (ITransaction tran = _session.BeginTransaction())
                {
                    try
                    {
                        _session.Delete(sprint);
                        tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        string msg = ex.Message;
                    }
                }
            }
        }
    }
}